/**
 * @ 从一个字符串里insert一个字符或一个字符串
 * 
 * @author	 wangshikun <wangshikun2010@gmail.com>
 * @copyright	(c) 2012 wangshikun <wangshikun2010@gmail.com>
 * @license	http://www.opensource.org/licenses/mit-license.php The MIT License
 * @package	default
 * @startpackage	default
 */

#include <stdio.h>
#include <cs50.h>
#include <string.h>

// 函数声明
void insertString(char text[], int start, char  insert[]);

// 主函数
int main(void) {
	
	// 输入
	printf("\n母字符串：");
	char *text = GetString();
	printf("sub: ");
	int start = GetInt();
	printf("char: ");
	char *string = GetString();

	// 调用函数
	insertString(text, start, string);

	return 0;
}

// insert the string
void insertString(char text[], int start, char insert[]) {
	int length1 = strlen(text);
	int length2 = strlen(insert);
	int i = 0, j = 0, k = 0;

	int length = length1 + length2;
	char *newString = malloc(sizeof(char) * (length + 1));

	// if delete from end
	if (start > length1 - 1) {
		start = length1 -1;
	}

	for (i=0; i<length1; i++) {
		newString[k++] = text[i];
		if (i == start) {
			for (j=0; j<length2; j++) {
				newString[k++] = insert[j];
			}
		}
	}	

	newString[k] = '\0';
	printf("%s\n", newString);
}
